package com.readboy.calculator;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.ginsmile.calculatorpro.R;

public class FlowService extends Service {
    private final String TAG="FlowService";
    public static boolean isStarted=false;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;

    private ImageButton enlarge;
    private ImageButton shrink;
    private View displayView;

    private String expression ="";
    private boolean last_equal = false;//上一次的按键是否为等号

    protected EditText text1;//第一行，用来显示按过等号之后的完整表达式
    protected EditText text2;//第二行，用来显示表达式和结果
    protected static boolean isSimple = false;//当前是否是简易计算器

    private View board;
    private View board2;

//    private int screen_width;
//    private int screen_height;


    private LinearLayout display;
    private Button[] buttons;
    private Button[] buttons2;
    private Button change_btn;
    private ImageButton exit_btn;

    private int angle_metric=0;
    private Intent intent;

    public MyBinder binder=new MyBinder();

    public class MyBinder extends Binder {
        public FlowService getService(){
            return FlowService.this;
        }
        public String getExpression(){
            Log.e(TAG,"getExpression:expression="+expression);

            return expression;
        }
//        public void setExpression(String s){
//            Log.e(TAG,"setExpression:s="+s);
//            expression=s;
//            text2.setText(expression);
//        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private void initCalculator(){
        change_btn = (Button)displayView.findViewById(R.id.change);
        change_btn.setVisibility(View.VISIBLE);
        change_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //更换键盘
                if(isSimple == true){
                    //缩放动画效果
                    board.setVisibility(View.INVISIBLE);
                    board2.setVisibility(View.VISIBLE);
                    ScaleAnimation sa = new ScaleAnimation(1.2f,1f,1.2f,1f,
                            Animation.RELATIVE_TO_SELF,1f,
                            Animation.RELATIVE_TO_SELF,1f);
                    sa.setDuration(300);
                    board2.startAnimation(sa);
                    isSimple = false;
                }else{
                    ScaleAnimation sa = new ScaleAnimation(1f,1.25f,1f,1.2f,
                            Animation.RELATIVE_TO_SELF,1f,
                            Animation.RELATIVE_TO_SELF,1f);
                    sa.setDuration(300);
                    board2.startAnimation(sa);

                    board2.setVisibility(View.INVISIBLE);
                    board.setVisibility(View.VISIBLE);
                    isSimple = true;
                }
            }
        });

        exit_btn=displayView.findViewById(R.id.exit_btn);
        exit_btn.setVisibility(View.VISIBLE);
        exit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                windowManager.removeView(displayView);

//               stopService(intent);
               isStarted=false;
            }
        });

        text1 = (EditText)displayView.findViewById(R.id.text1);
        text2 = (EditText)displayView.findViewById(R.id.text2);

        if (expression!=""){
            text2.setText(expression);
        }


//        text2.setText("126");


        //初始化计算器键盘
        buttons = new Button[18];
        buttons2 = new Button[31];
        initSimpleBoard(buttons);//初始化简易计算器键盘
        initScienceBoard(buttons2);//初始化科学计算器键盘
        board = (View)displayView.findViewById(R.id.board);
        board2 = (View)displayView.findViewById(R.id.board2);


//        if(savedInstanceState != null){
//            text1.setText(savedInstanceState.getString("text1"));
//            text2.setText(savedInstanceState.getString("text2"));
//            isSimple = savedInstanceState.getBoolean("isSimple");
//            Log.v("TAG==>","OKKOKOKO");
//        }
    }

    private void initFlowWindow(){
        windowManager= (WindowManager) getSystemService(WINDOW_SERVICE);
        layoutParams=new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        layoutParams.format= PixelFormat.RGBA_8888;
        layoutParams.gravity= Gravity.LEFT|Gravity.TOP;
        layoutParams.flags=WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width=520;
        layoutParams.height=800;
        layoutParams.x=300;
        layoutParams.y=300;


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onCreate() {
        super.onCreate();

//        isStarted=true;
//        initFlowWindow();
//        showFloatingWindow();
//        initCalculator();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String s=intent.getStringExtra("largeExpression");
        if (s!=""){
            expression=s;
//            text2.setText(expression);
        }
//        this.intent=intent;
        Log.e(TAG,"s="+s);
//        initFlowWindow();
        isStarted=true;
        initFlowWindow();
        showFloatingWindow();
        initCalculator();
//        return super.onStartCommand(intent, flags, startId);
        return START_NOT_STICKY;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void showFloatingWindow(){
        if (Settings.canDrawOverlays(this)){
            LayoutInflater inflater=LayoutInflater.from(this);
            displayView=inflater.inflate(R.layout.activity_main,null);

            enlarge=displayView.findViewById(R.id.enlarge_btn);
            shrink=displayView.findViewById(R.id.shrink_btn);
            displayView.setOnTouchListener(new FloatingOnTouchListener());
            windowManager.addView(displayView, layoutParams);

            enlarge.setVisibility(View.VISIBLE);
            shrink.setVisibility(View.GONE);

            enlarge.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(getApplicationContext(),"点击了",Toast.LENGTH_SHORT).show();
//                    Log.e("jay","FlowService:enlarge");
                    windowManager.removeView(displayView);
                    intent=new Intent(FlowService.this,MainActivity.class);
                    intent.putExtra("shrinkExpression",expression);
                    startActivity(intent);

                    isStarted=false;
                    isSimple=false;
                }
            });
//            drag_btn.setOnTouchListener(new FloatingOnTouchListener());
        }
    }


    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    x= (int) event.getRawX();
                    y= (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX= (int) event.getRawX();
                    int nowY= (int) event.getRawY();
                    int movedX=nowX-x;
                    int movedY=nowY-y;
                    x=nowX;
                    y=nowY;
                    layoutParams.x=layoutParams.x+movedX;
                    layoutParams.y=layoutParams.y+movedY;
                    windowManager.updateViewLayout(v,layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    private void initSimpleBoard(final Button[] buttons){
        buttons[0] = (Button)displayView.findViewById(R.id.zero);
        buttons[1] = (Button)displayView.findViewById(R.id.one);
        buttons[2] = (Button)displayView.findViewById(R.id.two);
        buttons[3] = (Button)displayView.findViewById(R.id.three);
        buttons[4] = (Button)displayView.findViewById(R.id.four);
        buttons[5] = (Button)displayView.findViewById(R.id.five);
        buttons[6] = (Button)displayView.findViewById(R.id.six);
        buttons[7] = (Button)displayView.findViewById(R.id.seven);
        buttons[8] = (Button)displayView.findViewById(R.id.eight);
        buttons[9] = (Button)displayView.findViewById(R.id.nine);

        buttons[10] = (Button)displayView.findViewById(R.id.empty);
        buttons[11] = (Button)displayView.findViewById(R.id.delete);
        buttons[12] = (Button)displayView.findViewById(R.id.divide);
        buttons[13] = (Button)displayView.findViewById(R.id.multiple);
        buttons[14] = (Button)displayView.findViewById(R.id.minus);
        buttons[15] = (Button)displayView.findViewById(R.id.plus);
        buttons[16] = (Button)displayView.findViewById(R.id.equal);
        buttons[17] = (Button)displayView.findViewById(R.id.dot);

        for (int i=0;i<=17;i++){
            buttons[i].setTextSize(getResources().getDimension(R.dimen.float_btn_text_size));
        }

        initCommonBtns(buttons);
    }

    //初始化科学计算器键盘
    private void initScienceBoard(final Button[] buttons){
        buttons[0] = (Button)displayView.findViewById(R.id.zero2);
        buttons[1] = (Button)displayView.findViewById(R.id.one2);
        buttons[2] = (Button)displayView.findViewById(R.id.two2);
        buttons[3] = (Button)displayView.findViewById(R.id.three2);
        buttons[4] = (Button)displayView.findViewById(R.id.four2);
        buttons[5] = (Button)displayView.findViewById(R.id.five2);
        buttons[6] = (Button)displayView.findViewById(R.id.six2);
        buttons[7] = (Button)displayView.findViewById(R.id.seven2);
        buttons[8] = (Button)displayView.findViewById(R.id.eight2);
        buttons[9] = (Button)displayView.findViewById(R.id.nine2);

        buttons[10] = (Button)displayView.findViewById(R.id.empty2);
        buttons[11] = (Button)displayView.findViewById(R.id.delete2);
        buttons[12] = (Button)displayView.findViewById(R.id.divide2);
        buttons[13] = (Button)displayView.findViewById(R.id.multiple2);
        buttons[14] = (Button)displayView.findViewById(R.id.minus2);
        buttons[15] = (Button)displayView.findViewById(R.id.plus2);
        buttons[16] = (Button)displayView.findViewById(R.id.equal2);
        buttons[17] = (Button)displayView.findViewById(R.id.dot2);

        initCommonBtns(buttons);


        //初始化剩余的12个按钮
        buttons[18] = (Button)displayView.findViewById(R.id.sin);
        buttons[19] = (Button)displayView.findViewById(R.id.cos);
        buttons[20] = (Button)displayView.findViewById(R.id.tan);
        buttons[21] = (Button)displayView.findViewById(R.id.ln);
        buttons[22] = (Button)displayView.findViewById(R.id.log);

        buttons[23] = (Button)displayView.findViewById(R.id.rad);
        buttons[30]=  (Button)displayView.findViewById(R.id.deg);

        buttons[24] = (Button)displayView.findViewById(R.id.power);
        buttons[25] = (Button)displayView.findViewById(R.id.sqrt);
        buttons[26] = (Button)displayView.findViewById(R.id.pi);
        buttons[27] = (Button)displayView.findViewById(R.id.left_parentheses);
        buttons[28] = (Button)displayView.findViewById(R.id.right_parentheses);
        buttons[29] = (Button)displayView.findViewById(R.id.e);

        for (int i=0;i<=30;i++){
            buttons[i].setTextSize(getResources().getDimension(R.dimen.float_btn_text_size));
        }
        buttons[18].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[18].getText() + "(";
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[19].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[19].getText() + "(";
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[20].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[20].getText() + "(";
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[21].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[21].getText() + "(";
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[22].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[22].getText() + "(";
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[23].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                buttons[23].setBackgroundColor(getResources().getColor(R.color.keyBackground_pressed));
                buttons[23].setEnabled(false);
                buttons[30].setEnabled(true);
                buttons[30].setBackgroundColor(getResources().getColor(R.color.keyBackground_normal));
                angle_metric=1;
            }
        });

        buttons[30].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttons[30].setBackgroundColor(getResources().getColor(R.color.keyBackground_pressed));
                buttons[30].setEnabled(false);
                buttons[23].setBackgroundColor(getResources().getColor(R.color.keyBackground_normal));
                buttons[23].setEnabled(true);
                angle_metric=0;
            }
        });
        buttons[24].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[24].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[25].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[25].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[26].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[26].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[27].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[27].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[28].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[28].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        buttons[29].setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[29].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
    }
    //初始化简易计算器，科学计算器相同的18个按钮
    private void initCommonBtns(final Button[] buttons){
        //添加监听事件
        //数字0～9
        for(int i = 0; i < 10; i++){
            final int m = i;
            buttons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(last_equal){
                        expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                        last_equal = false;
                    }
                    expression += buttons[m].getText();
                    text2.setText(expression);
                    text2.setSelection(expression.length());
                }
            });
        }
        //empty
        buttons[10].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                expression = "";
                text2.setText("0");
                text1.setText(null);
                last_equal = false;
            }
        });
        //delete
        buttons[11].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(expression.length() < 1){
                    return;
                }
                expression = expression.substring(0,expression.length()-1);
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        //divide
        buttons[12].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[12].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        //multiple
        buttons[13].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[13].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        //minus
        buttons[14].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[14].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        //plus
        buttons[15].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[15].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
        //equal
        buttons[16].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(last_equal) return;//如果上次还是按的等号，那么什么也不做

                //小小的动画效果
                AnimationSet animSet = new AnimationSet(true);
                TranslateAnimation ta = new TranslateAnimation(0,0,0,-100);
                ta.setDuration(80);
                AlphaAnimation aa = new AlphaAnimation(1f, 0f);
                aa.setDuration(75);
                animSet.addAnimation(ta);
                animSet.addAnimation(aa);
                text2.startAnimation(animSet);
                animSet.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        //动画结束之后计算
//                        text1.setText(expression + "=");
//                        text1.setSelection(expression.length()+1);//在第一行显示计算表达式
//                        try{
//                            expression = Calculate.calculate(expression);
//                            text2.setText(expression);//在第二行显示计算结果
//                        }catch(Exception exception){
//                            text2.setText("表达式错误!");//在第二行显示计算结果
//                            expression = "";
//                        }

                        int leftNum = 0;
                        int rightNum = 0;
                        for (int i = 0; i < expression.length(); i++) {
                            if (expression.charAt(i) == '(')
                                leftNum++;
                            if (expression.charAt(i) == ')')
                                rightNum++;
                        }
                        int missingNum = leftNum - rightNum; //缺失的 ) 数量
                        while (missingNum > 0) {
                            expression += ')';
                            missingNum--;
                        }
                        text1.setText(expression+"=");

//                        mathPast = "\n" + mathNow; //使得呈现的mathPast自动换行

                        ScienceCalculator scienceCalculator=new ScienceCalculator();
                        try{
                            double result = scienceCalculator.cal(expression, 6, angle_metric); //调用科学计算器

                            if (result == Double.MAX_VALUE)
                                expression = "Math Error";
                            else {
                                expression = String.valueOf(result);
                                if (expression.charAt(expression.length() - 2) == '.' && expression.charAt(expression.length() - 1) == '0') {
                                    expression = expression.substring(0, expression.length() - 2);
                                }
                            }

                            text2.setText(expression);
                        }catch (Exception e){
                            text2.setText("表达式错误");
                        }

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });


                // 为下一次按计算器键盘做准备。
                // 如果下次按的是数字，那么清空第二行重新输入第一个数。
                // 如果是非数字，那就当这次的结果是输入的第一个数，直接参与运算。
                last_equal = true;

            }


        });
        buttons[17].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(last_equal){
                    expression = "";//这次按的数字，如果上次按了等号，则清空表达式
                    last_equal = false;
                }
                expression += buttons[17].getText();
                text2.setText(expression);
                text2.setSelection(expression.length());
                last_equal = false;
            }
        });
    }

}
